package com.daily.daily_push.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.daily.daily_push.config.WxConfigNew;
import com.daily.daily_push.vo.NewArticle;
import com.daily.daily_push.vo.WxCpDefaultResult;
import com.daily.daily_push.vo.WxCpMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
@RestController
@Slf4j
@CrossOrigin
public class Test {
    @Resource
    RedisTemplate<String, String> redisTemplateString;

    @GetMapping("/test")
    public String sendTextcardMsg() {
    /*    String redirectUri = "https://8164c0cc874549a6aa31385aebfea4a8.apig.cn-east-3.huaweicloudapis.com";
        String wysqlj = "https://open.weixin.qq.com/connect/oauth2/authorize";
        String basePath = "D:\\commonTest\\";
        String bgtuPath = "D:\\commonTest\\tex\\";
        String appid = "wwe24d68910965e032";
        String status = "TEST6666";
        String agentid="1000002";
//重定向地址，需要带上会议室id
        String redirect_uri = URLEncoder.encode(redirectUri);
//生成二维码海报
        String url = wysqlj + "?appid=" + appid + "&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_privateinfo&state="+status+"&agentid="+agentid+"#wechat_redirect";
        String url3 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwe24d68910965e032&redirect_uri=https%3A%2F%2F8164c0cc874549a6aa31385aebfea4a8.apig.cn-east-3.huaweicloudapis.com&response_type=code&scope=snsapi_base&state=TEST6666#wechat_redirect";

        String url1 = "http://www.xiqianyangyi.com/leaveMessage";
        String path = basePath + System.currentTimeMillis() + ".png";
        File filea = QrCodeUtil.generate(url3,
                QrConfig.create(), //附带logo
                FileUtil.file(path)//写出到的文件
        );*/
        return "你好，访问成功了！";

    }

    @GetMapping("/test2")
    public RedirectView test2() {
        String redirectUri = "https://8164c0cc874549a6aa31385aebfea4a8.apig.cn-east-3.huaweicloudapis.com";
        String wysqlj = "https://open.weixin.qq.com/connect/oauth2/authorize";
        String basePath = "D:\\commonTest\\";
        String bgtuPath = "D:\\commonTest\\tex\\";
        String appid = "wwe24d68910965e032";
        String status = "TEST6666";
//重定向地址，需要带上会议室id
        String redirect_uri = URLEncoder.encode(redirectUri);
//生成二维码海报
        String url = wysqlj + "?appid=" + appid + "&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_base&state=" + status + "#wechat_redirect";

        String targetURL = url;
        System.out.println(url);
        RedirectView redirectView = new RedirectView(targetURL);
        redirectView.setStatusCode(HttpStatus.FOUND);
        return redirectView;


    }

    @GetMapping("/test3")
    public ResponseEntity<ByteArrayResource> test3() {
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwe24d68910965e032&redirect_uri=https%3A%2F%2F8164c0cc874549a6aa31385aebfea4a8.apig.cn-east-3.huaweicloudapis.com&response_type=code&scope=snsapi_base&state=TEST6666#wechat_redirect";
        QrConfig qrConfig = new QrConfig();
        qrConfig.setHeight(300);
        qrConfig.setWidth(300);
        ByteArrayOutputStream qrCodeStream = new ByteArrayOutputStream();
        QrCodeUtil.generate(url, qrConfig, "png", qrCodeStream);
        ByteArrayResource resource = new ByteArrayResource(qrCodeStream.toByteArray());
        IoUtil.close(qrCodeStream);

        return ResponseEntity.status(HttpStatus.OK)
                .header("Content-Type", "image/png")
                .header("Content-Disposition", "attachment; filename=qrcode.png")
                .body(resource);


    }

    @GetMapping("/test4")
    public String test4() {

        WxCpDefaultResult wwe24d68910965e032 = WxConfigNew.getAccessToken(redisTemplateString, "wwe24d68910965e032", "00b6rPIvdzgFi7sdyvJNDjiRMurzIsLbNFntqaIGRmU");

        System.out.println(wwe24d68910965e032);
        WxCpMessage newsMsg = new WxCpMessage();
        //设置消息类型
        newsMsg.setMsgType("markdown");
        newsMsg.setAgentId(1000002);
        //设置发送用户
        newsMsg.setToUser("ZhanKui|zhanfang3");

        if (newsMsg.getMsgType().equals("markdown")){
            newsMsg.setContent("您的会议室已经预定，稍后会同步到`邮箱`  \n>**事项详情**  \n>事　项：<font color=\"info\">开会</font>  \n>组织者：@miglioguan  \n>参与者：@miglioguan、@kunliu、@jamdeezhou、@kanexiong、@kisonwang  \n>  \n>会议室：<font color=\"info\">广州TIT 1楼 301</font>  \n>日　期：<font color=\"warning\">2018年5月18日</font>  \n>时　间：<font color=\"comment\">上午9:00-11:00</font>  \n>  \n>请准时参加会议。  \n>  \n>如需修改会议信息，请点击：[修改会议信息](https://work.weixin.qq.com)");
        }
        if (newsMsg.getMsgType().equals("news")){
            List<NewArticle> articlesList = new ArrayList<>();
            NewArticle newArticle = new NewArticle();
            //发送的标题
            newArticle.setTitle("中秋节礼品领取");
            //发送内容
            newArticle.setDescription("今年中秋节公司有豪礼相送");
            //图片地址
            newArticle.setPicUrl("http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png");
            //设置跳转；可以自己制作一个网页
            newArticle.setUrl("www.baidu.com");
            //添加到List集合
            articlesList.add(newArticle);
            newsMsg.setArticles(articlesList);
        }

        String json = newsMsg.toJson();
        System.out.println("json :"+json );
        System.out.println("token :"+wwe24d68910965e032.getAccess_token() );
        String result = HttpRequest.post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+wwe24d68910965e032.getAccess_token()).header("Content-Type","application/json").body(json).execute().body();


        JSONObject jsonObject = JSON.parseObject(result);

        if (jsonObject.get("msgid") != null) {
            System.out.println("!11111111111111111111111111111111111111111");
        } else {
            System.out.println("2222222222222222222222222222222222222222");
        }
        return result;

//        return ResponseEntity.ok(wwe24d68910965e032);

    }



    @GetMapping("/constructOauthLink")
    public ResponseEntity<?> constructOauthLink() {

        //微信固定API地址
        String wysqlj = "https://open.weixin.qq.com/connect/oauth2/authorize";

        //对科接口回调地址进行url编码
//        String redirectUriEncoder = URLEncoder.encode(wxRedirectUri);
        //构造授权连接  snsapi_base：静默授权，可获取成员的基础信息（UserId与DeviceId）,snsapi_privateinfo：手动授权，可获取成员的详细信息，包含头像、二维码等敏感信息。
        String url = "";

//      return "redirect:" + url;
        log.info("授权链开始进行重定向url: {}", url);
        return ResponseEntity.status(HttpStatus.FOUND)
                .header("Location", "https://www.baidu.com/")
                .build();

    }

}
